import React from 'react';
import {Table, Row, Col, Form, Input, Icon, InputNumber, Radio, DatePicker, Select, Upload, Button, Switch, Modal, Popconfirm, Tabs, message} from 'antd';
import BizParams from '../../../components/commons/BizParams'

const R = require('ramda');


const FormItem = Form.Item;
const RadioGroup = Radio.Group;
const Option = Select.Option;
const TabPane = Tabs.TabPane;

export default Form.create({wrappedComponentRef: true})(class CostList extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            tempSelectOrderKeys: [],
            tempSelecthistoryKeys: [],
            tempSelecforexKeys: [],
            tempSelectOrderChargeKeys: []
        };
    }

    handleResetFields = () => {
        this.props.form.resetFields();
        this.setState({tempSelectOrderKeys: [], tempSelecthistoryKeys: [], tempSelecforexKeys:[], tempSelectOrderChargeKeys: [] })
        this.props.dispatch({
            type: 'customerManage/setUnsettleorder',
            payload:{
                list: []
            }
        });

        this.props.dispatch({
            type: 'customerManage/setStatetemntDetail',
            payload:{
                data: {}
            }
        });
    }

    handleStatetemntDetail = () => {

        if (R.isEmpty(this.props.payload.orderIds)) {
            if (R.isEmpty(this.props.payload.historyAmtIds)) {
                message.error("请选择订单或余额结算！");
                return;
            }

        }else{
            this.props.dispatch({
                type: 'customerManage/getStatetemntDetail',
                payload: {
                    type: this.props.statementType,
                    cstId: this.props.cstId,
                    orderIds: this.props.payload.orderIds
                }
            });
        }
        this.props.setSetpTwoDisable(false);
    }


    setIdarray = (selectedRows, type) => {
        let ids = [];
        let orderChargesCost = [];
        for(let i =0; i< selectedRows.length; i++){
            ids.push(selectedRows[i].id);
            if(type == "orderCharge"){
                orderChargesCost.push(selectedRows[i].cost);
            }
        }

        let payload ={};
        payload.orderChargesStatement = orderChargesCost;

        if(R.isNil(type) ){
            return;

        }else if(type == "order") {
            payload.orderIds = ids;

        }else if(type == "historyAmt") {
            payload.historyAmtIds = ids;

        }else if(type == "forex") {
            payload.forexIds = ids;

        }else if(type == "deposit") {
            payload.depositids = ids;

        }else if(type == "orderCharge"){
            payload.orderChargesIds = ids;
        }
        this.props.setPayload(payload);
    }

    getNoOrderDeposit = () => {
        let deposit = [];
        let depositIds = [];
        let selectDeposit =[];
        let forexIds = this.props.payload.forexIds;
        let payload ={};



        if(R.isEmpty(forexIds) || R.isNil(forexIds)){
            payload.depositids = depositIds;
            this.props.setPayload(payload);
            return deposit;
        }

        deposit = this.props.customerManage.statetemntDetail.deposits;

        if(R.isNil(deposit) || R.isEmpty(deposit)){
            payload.depositids = depositIds;
            this.props.setPayload(payload);
            return deposit;
        }

        for(let i =0; i< forexIds.length; i++){
            for(let j=0; j< deposit.length; j++){
                if(forexIds[i] == deposit[j].forexid){
                    if(!R.contains(deposit[j].id, depositIds)){
                        selectDeposit.push( deposit[j]);
                        depositIds.push(deposit[j].id);
                    }

                }
            }
        }

        depositIds = R.uniqBy(Math.abs, depositIds);
        payload.depositids = depositIds;
        this.props.setPayload(payload);
        return selectDeposit;

    }

    /**
     * 无订单 释放保证金
     * @returns {Array}
     */
    getNoOrderDepositRecord = (deposits) => {
        let depositRecords = [];
        let depositRecordIds = [];
        let selectDepositRecords =[];
        let payload ={};

        if(R.isEmpty(deposits) || R.isNil(deposits)){
            payload.depositRecordIds = depositRecordIds;
            this.props.setPayload(payload);
            return depositRecords;
        }

        depositRecords = this.props.customerManage.statetemntDetail.depositRecord;

        if(R.isNil(depositRecords) || R.isEmpty(depositRecords)){
            payload.depositRecordIds = depositRecordIds;
            this.props.setPayload(payload);
            return depositRecords;
        }

        for(let i =0; i< deposits.length; i++){
            for(let j=0; j< depositRecords.length; j++){
                if(deposits[i].id == depositRecords[j].depositid){
                    if(!R.contains(depositRecords[j].id, depositRecordIds)){
                        selectDepositRecords.push( depositRecords[j]);
                        depositRecordIds.push(depositRecords[j].id);
                    }

                }
            }
        }

        depositRecordIds = R.uniqBy(Math.abs, depositRecordIds);
        payload.depositRecordIds = depositRecordIds;
        this.props.setPayload(payload);
        return selectDepositRecords;
    }



    forexsColumns = [
        {title: '外汇编号', dataIndex: 'id', key: 'id'},
        {title: '订单编号', dataIndex: 'orderno', key: 'orderno'},
        {title: '产生时间', dataIndex: 'createtime', key: 'createtime'},
        {title: '收汇币种', dataIndex: 'recamountunit', key: 'recamountunit'},
        {title: '收汇金额', dataIndex: 'recamount', key: 'recamount'},
        {title: '金额(CNY)', dataIndex: 'actualamount', key: 'actualamount'},
        {title: '客户汇率', dataIndex: 'cstexchangerate', key: 'cstexchangerate'},
        {title: '外汇关联金额', dataIndex: 'relateamount', key: 'relateamount'},
        {title: '订单关联金额', dataIndex: 'odrelateamount', key: 'odrelateamount'},
        {title: '出口币种', dataIndex: 'currencytype', key: 'currencytype'},
        // {title: '备注', dataIndex: '22', key: '22'},
        ];


    historyAmtsColumns = [
        {title: '产生时间', dataIndex: 'createtime', key: 'createtime'},
        {title: '币种', dataIndex: 'currency', key: 'currency'},
        {title: '金额', dataIndex: 'amount', key: 'amount'},
        {title: '结算单号', dataIndex: 'stateid', key: 'stateid'},
        // {title: '备注', dataIndex: 'memo', key: 'memo'},
        {title: 'id', dataIndex: 'id', key: 'id',  colSpan:1, width:0 , filterDropdownVisible: false},
        ];


    drawbackColumns = [
        {title: '产生时间', dataIndex: 'createtime', key: 'createtime'},
        {title: '币种', key: 'taxplayercode', render(record) {return "CNY"}},
        {title: '金额', dataIndex: 'amount', key: 'amount'},
        {title: '订单编号', dataIndex: 'orderid', key: 'orderid'},
        {title: '合同协议号', dataIndex: 'contractno', key: 'contractno'},
        {title: '备注', dataIndex: 'memo', key: 'memo'},
        ];


    releaseDepositsColumns = [
        {title: '保证金类型',  key: 'name', render(record) {return "释放保证金"}},
        {title: '产生时间', dataIndex: 'createtime', key: 'createtime'},
        {title: '币种', render(record) {return "CNY"}},
        {title: '金额(CNY)', dataIndex: 'amount', key: 'amount'},
        {title: '保证金单号', dataIndex: 'depositno', key: 'depositno'},
        {title: '备注', dataIndex: 'memo', key: 'memo'},
        ];

    depositsColumns = [
        {title: '保证金类型',  key: 'name', render(record) {return "保证金"}},
        {title: '产生时间', dataIndex: 'createtime', key: 'createtime'},
        {title: '保证金金额', dataIndex: 'amount', key: 'amount'},
        {title: '外汇金额(CNY)', dataIndex: 'recamount', key: 'recamount'},
        {title: '保证金单号', dataIndex: 'depositno', key: 'depositno'},
        {title: '对应外汇', dataIndex: 'forexid', key: 'forexid'},
        ];

    orderCostColumns = [
        {title: '币种', dataIndex: 'chargecurrency', key: 'chargecurrency'},
        {title: '金额', dataIndex: 'cost', key: 'cost'},
        {title: '订单编号', dataIndex: 'orderno', key: 'orderno'},
        {title: '合同协议号', dataIndex: 'contractno', key: 'contractno'},
        {title: '费用类型', dataIndex: 'chargetypeName', key: 'chargetypeName'},
        {title: '备注', dataIndex: 'memo', key: 'memo'},
        ];

    orderColumns = [
        {title: '订单编号', dataIndex: 'orderno', key: 'orderno'},
        {title: '客户名称', dataIndex: 'companyname', key: 'companyname'},
        {title: '合同协议号', dataIndex: 'contractno', key: 'contractno'},
        {title: '报关方式', dataIndex: 'declarationtypeName', key: 'declarationtypeName'},
        {title: '报关口岸', dataIndex: 'portofentryName', key: 'portofentryName'},

        {title: '外汇收齐状态',  key: 'foxerstatus', render(record) {
            if("1" == record.foxerstatus){
                return "已收齐"
            }else{
                return "未收齐"
            }}},

        {title: '退税款到账状态',  key: 'transferaccountstatus', render(record) {
            if("0" == record.transferaccountstatus){
                return "待退税"
            }else if("1" == record.transferaccountstatus){
                return "退税到账"
            }else if("2" == record.transferaccountstatus){
                return "暂缓退税"
            }else if("3" == record.transferaccountstatus){
                return "税局发函"
            }}},

        {title: '订单状态' , key: 'status', render(record) {
            if("1" == record.status){
                return "草稿"
            }else if("2" == record.status){
                return "待通关审核"
            }else if("3" == record.status){
                return "待补充资料"
            }else if("4" == record.status){
                return "待签确认函"
            }else if("5" == record.status){
                return "待报关"
            }else if("6" == record.status){
                return "报关中"
            }else if("7" == record.status){
                return "办理完毕"
            }}},

        {title: '预计报关时间', dataIndex: 'exportdeclarationdate', key: 'exportdeclarationdate'},
        {title: 'id', dataIndex: 'id', key: 'id',  colSpan:1, width:0 , filterDropdownVisible: false},
        ];

    render() {
        const { getFieldDecorator } = this.props.form;
        let dataSource = R.isNil(this.props.dataSource) ? {} : this.props.dataSource;
        let formItemLayout = {
            labelCol: { xs: { span: 24 }, sm: { span: 8 } },
            wrapperCol: { xs: { span: 24 }, sm: { span: 12 } }
        };
        let values = this.props.form.getFieldsValue();
        let pagination = {

        }

        let historyAmtsRowSelection = {

            onChange: (selectedRowKeys, selectedRows) => {
                this.setState({tempSelecthistoryKeys: selectedRowKeys,})
                this.setIdarray(selectedRows, "historyAmt");
                this.props.setSetpTwoDisable(true);
            },
            selectedRowKeys : this.state.tempSelecthistoryKeys,

        };

        let orderSelection = {
            
            onChange: (selectedRowKeys, selectedRows) => {
                
                this.setState({tempSelectOrderKeys: selectedRowKeys,})
                this.setIdarray(selectedRows, "order");
                this.props.setSetpTwoDisable(true);
            },

            selectedRowKeys : this.state.tempSelectOrderKeys,
        };

        let forexSelection = {
            onChange: (selectedRowKeys, selectedRows) => {
                this.setState({tempSelecforexKeys: selectedRowKeys,})
                this.setIdarray(selectedRows, "forex");
            },

            selectedRowKeys : this.state.tempSelecforexKeys,
        };

        let orderChargeSelection = {
            onChange: (selectedRowKeys, selectedRows) => {

                this.setState({tempSelectOrderChargeKeys: selectedRowKeys,})
                this.setIdarray(selectedRows, "orderCharge");
            },

            selectedRowKeys : this.state.tempSelectOrderChargeKeys,
        };


        let deposits = this.props.statementType == 1 ? this.getNoOrderDeposit() :
            (R.isNil(this.props.customerManage.statetemntDetail.deposit) ? this.props.customerManage.statetemntDetail.deposits :
            this.props.customerManage.statetemntDetail.deposit);

        let depositRecords = this.props.statementType == 1 ? this.getNoOrderDepositRecord(deposits) : this.props.customerManage.statetemntDetail.depositRecord;

        return (
            <div>
                <form></form>
                <Tabs tabPosition={'top'}>
                    <TabPane tab="历史余额" key="1">
                        <Table dataSource={this.props.customerManage.historyAmtList} columns={this.historyAmtsColumns} bordered={true} rowSelection={historyAmtsRowSelection}  size={'middle'} pagination={false} />
                    </TabPane>
                </Tabs>
                {this.props.statementType == "2" ?
                    <div>
                        <Tabs tabPosition={'top'}>
                            <TabPane tab="订单列表" key="1">
                                <div>
                                    <Table dataSource={this.props.customerManage.unsettleorderList} columns={this.orderColumns}
                                           rowSelection={orderSelection} bordered={true} size={'middle'}
                                           pagination={false} scroll={{x: true}}
                                    />
                                </div>
                            </TabPane>
                        </Tabs>
                    </div>
                    :
                    ""}

                {this.props.statementType == 2 ?
                    <Button type="primary" icon="className" size={'default'} disabled={this.props.disabled} onClick={this.handleStatetemntDetail.bind(this)}
                            style={{marginLeft:10, marginBottom: 20}}>确定结算</Button>
                    : ""}

                <Tabs tabPosition={'top'}>
                    <TabPane tab="应支付" key="1">
                        <div>
                            <p>外汇</p>
                                <Table dataSource={R.isNil(this.props.customerManage.statetemntDetail.forex) ? this.props.customerManage.statetemntDetail.forexs :
                                    this.props.customerManage.statetemntDetail.forex} columns={this.forexsColumns} bordered={true} size={'middle'}
                                      rowSelection={this.props.statementType == "1" ? forexSelection : ""} pagination={false}/>
                            <br/>

                            <p>退税融资款</p>
                            <Table dataSource={this.props.customerManage.statetemntDetail.taxRefundFinance} columns={this.drawbackColumns} bordered={true} size={'middle'} />
                            <br/>

                            <p>释放保证金</p>
                            <Table dataSource={depositRecords} columns={this.releaseDepositsColumns} bordered={true} size={'middle'} />
                        </div>
                    </TabPane>

                    <TabPane tab="应减扣" key="2">
                        <p>订单费用</p>
                        <Table dataSource={this.props.customerManage.statetemntDetail.orderCharge} columns={this.orderCostColumns} bordered={true}
                               size={'middle'} rowSelection={orderChargeSelection} pagination={false} />
                        <br/>

                        <p>保证金</p>
                        <Table dataSource={deposits} columns={this.depositsColumns} bordered={true} size={'middle'}/>
                    </TabPane>
                </Tabs>


            </div>

        )
    }
})


